from machine import Pin
from machine import Timer
from time import sleep_ms
import time
import bluetooth

# 定义GPIO引脚，L表示左，R表示右，fw表示前轮，bw表示后轮，1表示向前，0表示向后
Lfw1 = Pin(10,Pin.OUT)     # GPIO10引脚，左前轮电机向前
Lfw0 = Pin(7,Pin.OUT)      # GPIO7引脚，左前轮电机向后
Rfw1 = Pin(19,Pin.OUT)     # GPIO19引脚，右前轮电机向前
Rfw0 = Pin(8,Pin.OUT)      # GPIO8引脚，右前轮电机向后
Lbw1 = Pin(3,Pin.OUT)      # GPIO3引脚，左后轮电机向前
Lbw0 = Pin(2,Pin.OUT)      # GPIO2引脚，左后轮电机向后
Rbw1 = Pin(6,Pin.OUT)      # GPIO6引脚，右后轮电机向前
Rbw0 = Pin(18,Pin.OUT)     # GPIO18引脚，右后轮电机向后

BLE_MSG = ""

# 车向前进
def cargo():
    Lfw1.value(1)
    Lfw0.value(0)
    Rfw1.value(1)
    Rfw0.value(0)
    Lbw1.value(1)  
    Lbw0.value(0) 
    Rbw1.value(1)
    Rbw0.value(0)
    
# 车向后退
def carback():    
    Lfw1.value(0)
    Lfw0.value(1)
    Rfw1.value(0)
    Rfw0.value(1)
    Lbw1.value(0) 
    Lbw0.value(1)
    Rbw1.value(0)
    Rbw0.value(1)    
    
# 车向左水平运动
def carleft():
    Lfw1.value(1)
    Lfw0.value(0)    
    Rfw1.value(0)
    Rfw0.value(1)
    Lbw1.value(0) 
    Lbw0.value(1)
    Rbw1.value(1)
    Rbw0.value(0) 

# 车向右水平运动
def carright():
    Lfw1.value(0)
    Lfw0.value(1)
    Rfw1.value(1)
    Rfw0.value(0)
    Lbw1.value(1) 
    Lbw0.value(0)
    Rbw1.value(0)
    Rbw0.value(1)     
    
# 车停止
def carstop():
    Lfw1.value(0)
    Lfw0.value(0)
    Rfw1.value(0)
    Rfw0.value(0)
    Lbw1.value(0) 
    Lbw0.value(0)
    Rbw1.value(0)
    Rbw0.value(0) 

# 车向左转圈
def bigleft():   
    Lfw1.value(0)
    Lfw0.value(1)
    Rfw1.value(1)
    Rfw0.value(0)
    Lbw0.value(1)
    Lbw1.value(0)
    Rbw1.value(1)
    Rbw0.value(0)   

# 车向右转圈
def bigright():   
    Lfw1.value(1)
    Lfw0.value(0)    
    Rfw1.value(0)
    Rfw0.value(1)
    Lbw0.value(0)
    Lbw1.value(1)
    Rbw1.value(0)
    Rbw0.value(1)     
    
    
class ESP32_BLE():
    #蓝牙初始化
    def __init__(self, name):
        self.led = Pin(12, Pin.OUT)     #配置LED灯引脚为输出模式
        self.timer1 = Timer(0)          #配置定时器
        self.name = name
        self.ble = bluetooth.BLE()      #创建蓝牙对象
        self.ble.active(True)           #开启蓝牙
        self.ble.config(gap_name=name)  #配置蓝牙信息
        self.disconnected()             #设置定时器中断
        self.ble.irq(self.ble_irq)      #蓝牙时间处理
        self.register()                 #配置蓝牙的uuid
        self.ble.gatts_write(self.rx, bytes(100))#默认蓝牙只接收20字节，这里更改为接收100字节
        self.advertiser()               #蓝牙广播
        self.ok = 0

    #蓝牙连接，关闭LED灯
    def connected(self):
        self.timer1.deinit()
        self.led.value(0)
        print("connected ok")

    #蓝牙未连接，LED闪烁
    def disconnected(self):        
        self.timer1.init(period=100, mode=Timer.PERIODIC, callback=lambda t: self.led.value(not self.led.value()))

    #蓝牙事件处理
    def ble_irq(self, event, data):
        global BLE_MSG
        if event == 1: #_IRQ_CENTRAL_CONNECT 手机连接了此设备
            self.connected()
        elif event == 2: #_IRQ_CENTRAL_DISCONNECT 手机断开此设备
            if self.ok==0:
                self.advertiser()
                self.disconnected()
        elif event == 3: #_IRQ_GATTS_WRITE 手机发送了数据 
            buffer = self.ble.gatts_read(self.rx)
            BLE_MSG = buffer.decode('UTF-8').strip()
            
    #蓝牙UUID配置
    def register(self): 
        service_uuid = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
        reader_uuid = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
        sender_uuid = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'

        services = (
            (
                bluetooth.UUID(service_uuid), 
                (
                    (bluetooth.UUID(sender_uuid), bluetooth.FLAG_NOTIFY), 
                    (bluetooth.UUID(reader_uuid), bluetooth.FLAG_WRITE),
                )
            ), 
        )

        ((self.tx, self.rx,), ) = self.ble.gatts_register_services(services)


    #蓝牙广播配置
    def advertiser(self):
        name = bytes(self.name, 'UTF-8')
        adv_data = bytearray('\x02\x01\x02') + bytearray((len(name) + 1, 0x09)) + name
        self.ble.gap_advertise(100, adv_data)
        print("等待连接：%s" % adv_data)
        print("\r\n")



if __name__ == "__main__":
    try:
        # 车先待命
        carstop() 
        
        # 配置蓝牙
        ble = ESP32_BLE("ESP32C3BLE")

        # 配置LED
        led = Pin(12, Pin.OUT)
      

        while True:
            if len(BLE_MSG)>0:
                if BLE_MSG in ["!B507","!B606","!B705","!B804","!B10;","!B20:","!B309","!B408","stop"]: #松开按键停止
                    print(">>%s<<————停止" % BLE_MSG)
                    carstop() 
                elif BLE_MSG == "!B516":  # 按下app的上键向前
                    print(">>%s<<————向前" % BLE_MSG)
                    cargo()
                elif BLE_MSG == "!B615":  # 按下app的下键向后
                    print(">>%s<<————向后" % BLE_MSG)
                    carback()
                elif BLE_MSG == "!B714":  # 按下app的左键向左水平运动
                    print(">>%s<<————向左" % BLE_MSG)
                    carleft()
                elif BLE_MSG == "!B813":  # 按下app的右键向右水平运动
                    print(">>%s<<————向右" % BLE_MSG)
                    carright()
                elif BLE_MSG == "!B11:":  # 按下app的数字1左转圈
                    print(">>%s<<————左转圈" % BLE_MSG)
                    bigleft()
                elif BLE_MSG == "!B219":  # 按下app的数字2右转圈
                    print(">>%s<<————右转圈" % BLE_MSG)
                    bigright()
                BLE_MSG = ""
            sleep_ms(100)
        
    except KeyboardInterrupt:
        pass
  